package com.arcbbs.controller;

import com.arcbbs.annotation.GlobalInterceptor;
import com.arcbbs.config.WebConfig;
import com.arcbbs.constant.BaseConstant;
import com.arcbbs.exception.BaseException;
import com.arcbbs.result.Result;
import com.arcbbs.utils.StringTools;
import com.sun.deploy.net.HttpResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Resource
    private WebConfig webConfig;

    @RequestMapping("/upload")
    @GlobalInterceptor(checkLogin = true)
    public Result uploadImage(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String fileExtName = StringTools.getFileSuffix(fileName);
        if (!ArrayUtils.contains(BaseConstant.IMAGE_SUFFIX, fileExtName)) {
            throw new BaseException("后缀名不正确");
        }
        String path = copyfile(file);
        Map<String, String> map = new HashMap<>();
        map.put("fileName", path);
        return Result.success(map);
    }

    private String copyfile(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String fileExtName = StringTools.getFileSuffix(fileName);
            String fileRealName = StringTools.getFinalString(15) + fileName;
            String folderpath = webConfig.getProjectFolder() + "/file/temp/";
            File foder = new File(folderpath);
            if (!foder.exists()) {
                foder.mkdir();
            }
            File uploadfile = new File(folderpath + "/" + fileRealName);
            file.transferTo(uploadfile);
            return "temp" +"/"+ fileRealName;

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("上传文件失败");


        }
    }

    @RequestMapping("/getImage/{imageFolder}/{imageName}")
    public void getImage(HttpServletResponse httpResponse, @PathVariable("imageFolder") String imageFolder, @PathVariable("imageName") String imageName) {
        readImage(httpResponse, imageFolder, imageName);
    }

    private void readImage(HttpServletResponse response, String imageFolder, String imageName) {
        ServletOutputStream sos = null;
        FileInputStream in = null;
        ByteArrayOutputStream baos = null;
        System.out.println(imageFolder+"/123");
        System.out.println(imageName+"/123");
        try {
            System.out.println("123456");
            if (StringTools.isEmpty(imageFolder) || StringUtils.isBlank(imageName)) {
                return;
            }
            System.out.println("1234567");
            String imageSuffix = StringTools.getFileSuffix(imageName);
            System.out.println("1234568"+imageSuffix);
            String filePath = webConfig.getProjectFolder() + BaseConstant.FILE_FOLDER_FILE  + imageFolder + "/" + imageName;
            System.out.println("1234569"+filePath);
            System.out.println(imageFolder);
            if (BaseConstant.FILE_FOLDER_TEMP_2.equals(imageFolder)) {
                System.out.println("123");
                filePath = webConfig.getProjectFolder() + BaseConstant.FILE_FOLDER_FILE + imageFolder + "/" + imageName;
            } else if (imageFolder.contains(BaseConstant.FILE_FOLDER_AVATAR_NAME)) {
                System.out.println("456");
                filePath = webConfig.getProjectFolder() + BaseConstant.FILE_FOLDER_FILE + imageFolder + imageName;
            }
            File file = new File(filePath);
            if (!file.exists()) {
                return;
            }
            imageSuffix = imageSuffix.replace(".", "");
            if (!BaseConstant.FILE_FOLDER_AVATAR_NAME.equals(imageFolder)) {
                response.setHeader("Cache-Control", "max-age=2592000");
            }
            response.setContentType("image/" + imageSuffix);
            in = new FileInputStream(file);
            sos = response.getOutputStream();
            baos = new ByteArrayOutputStream();
            int ch = 0;
            while (-1 != (ch = in.read())) {
                baos.write(ch);
            }
            sos.write(baos.toByteArray());
        } catch (Exception e) {
            System.out.println(e);
            throw new BaseException("读取图片异常");
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    throw new BaseException("读取图片异常");
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    throw new BaseException("读取图片异常");
                }
            }
        }
    }

}
